package service

import (
	"core/coreentity"
	"core/coreservice"
	"core/corestruct"
	"core/coreutil"
	"core/myerrors"
	"ht/api/htmenu/data"
)

type mainService struct {
}

// Detail 菜单详情
func (p *mainService) Detail(mm *corestruct.IdModel, ctx *corestruct.HttpContext) (*data.HtMenuDto, error) {
	var r = &data.HtMenuDto{Id: mm.Id}
	var db = ctx.DB

	var err = db.Model(&coreentity.HtMenu{}).Find(r).Error
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}

	if r.HtpageId > 0 {
		var mpage = &coreentity.HtPage{Id: r.HtpageId}
		err = db.Find(mpage).Error
		if err != nil {
			return nil, myerrors.NewByErr(err)
		}
		r.Code = mpage.Code
		r.P1 = mpage.P1
		r.P2 = mpage.P2
		r.P3 = mpage.P3
		r.P4 = mpage.P4
	}
	return r, nil
}

// InsertInit 插入初始化
func (p *mainService) InsertInit(mm *data.HtMenuInsertQto, ctx *corestruct.HttpContext) (*data.HtMenuDto, error) {
	var r = &data.HtMenuDto{
		Id:         coreutil.IdUtil.GetId(),
		Pid:        mm.Id,
		HtplatId:   mm.HtplatId,
		Code:       "",
		Name:       "",
		Lx:         mm.Lx,
		HtpageId:   0,
		HtactionId: 0,
		Imgurl:     "layui-icon-spread-left",
		P1:         "",
		P2:         "",
		P3:         "",
		P4:         "",
		Sortno:     0,
		Memo:       "",
	}
	var db = ctx.DB

	var sortno = int64(0)
	var fmodel = &coreentity.HtMenu{Pid: r.Pid, HtplatId: r.HtplatId}
	err := db.Model(fmodel).
		Where(fmodel).
		Select("max(sortno)").
		Scan(&sortno).
		Error
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}
	return r, nil
}

// CheckExistByEname
// 检查菜单名是不是存在
func (p *mainService) CheckExistByEname(name string, htplatId, pid, id int64, ctx *corestruct.HttpContext) (bool, error) {
	var m = &coreentity.HtMenu{Name: name, HtplatId: htplatId, Pid: pid}
	tx := ctx.DB.Where(m).
		Where("id!=?", id).
		Select("id").
		Find(m)
	if tx.Error != nil {
		return false, myerrors.NewByErr(tx.Error)
	}
	return m.Id > 0, nil
}

// Insert
// 插入用户
func (p *mainService) Insert(mm *data.HtMenuDto, ctx *corestruct.HttpContext) (int64, error) {
	bExist, myerr := p.CheckExistByEname(mm.Name, mm.HtplatId, mm.Pid, mm.Id, ctx)
	if myerr != nil {
		return 0, myerr
	}
	if bExist == true {
		return 0, myerrors.New("菜单名称重复")
	}

	var db = ctx.DB
	tx := coreservice.BaseService.InsertByDto(mm, &coreentity.HtRoleMenu{}, db)

	if tx.Error != nil {
		return 0, myerrors.NewByErr(tx.Error)
	}
	return mm.Id, nil
}

// Update
// 修改用户
func (p *mainService) Update(mm *data.HtMenuDto, ctx *corestruct.HttpContext) (int64, error) {
	bExist, myerr := p.CheckExistByEname(mm.Name, mm.HtplatId, mm.Pid, mm.Id, ctx)
	if myerr != nil {
		return 0, myerr
	}
	if bExist == true {
		return 0, myerrors.New("菜单名称重复")
	}

	var db = ctx.DB
	tx := coreservice.BaseService.UpdateByDto(mm, &coreentity.HtRoleMenu{}, db)

	if tx.Error != nil {
		return 0, myerrors.NewByErr(tx.Error)
	}
	return mm.Id, nil
}

var (
	MainService = &mainService{}
)
